// pages/album/upload.js
import request from '../../utils/request'
import WxNotificationCenter from '../../utils/WxNotificationCenter'

const app = getApp()
const qiniuUploader = require('../../utils/qiniuUploader')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    albumId: 0,
    text: '',
    location: null,
    isRedpackPost: false,
    medias: [],
    upToken: '',
    account: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    this.setData({
      albumId: options.id,
      medias: JSON.parse(options.medias)
    })
    app.getUploadToken(function (err, token) {
      if (!err) {
        that.setData({
          upToken: token,
          account: app.globalData.account
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 选择照片或视频
   */
  chooseMedia: function (e) {
    let that = this
    let medias = this.data.medias
    wx.showActionSheet({
      itemList: [
        '添加图片',
        '添加视频'
      ],
      success: function (res) {
        if (res.tapIndex == 0) {
          let count = 9 - medias.length
          // 添加图片
          wx.chooseImage({
            count: count,
            sourceType: ['album'],
            success: function (res) {
              for (let i = 0; i < res.tempFilePaths.length; i++) {
                let item = { path: res.tempFilePaths[i], type: 0 }
                medias.push(item)
              }
              that.setData({
                medias: medias
              })
            },
          })
        } else {
          // 添加视频
          wx.chooseVideo({
            sourceType: ['album'],
            success: function(res) {
              let item = { path: res.tempFilePath, type: 1, duration: res.duration }
              medias.push(item)
              that.setData({
                medias: medias
              })
            }
          })
        }
      }
    })
  },

  /*
   * 移除添加的文件
   */
  removeMedia: function (e) {
    let index = e.currentTarget.dataset.index
    let medias = this.data.medias
    medias.splice(index, 1)
    this.setData({ medias: medias })
  },

  /*
   * 文本变更
   */
  textChange: function (e) {
    this.setData({
      text: e.detail.value
    })
  },

  /*
   * 选择地理位置
   */
  chooseLocation: function (e) {
    let that = this
    wx.chooseLocation({
      success: function(res) {
        that.setData({
          location: res
        })
      },
    })
  },

  switchChange: function(e) {
    this.setData({
      isRedpackPost: e.detail.value
    })
  },

  /*
   * 提交确认发布
   * 先保存，再上传图片
   */
  savePost: function () {
    let data = this.data
    if (!data.medias.length) {
      return wx.showToast({
        title: '请添加上传图片',
        image: '/images/icon/icon_attention.png'
      })
    }
    let that = this
    wx.showLoading({
      mask: true,
      title: '正在保存...',
    })
    let url = app.globalData.apiHost + '/albums/' + data.albumId + '/posts/'
    let formData = {
      album: data.albumId,
      text: data.text,
      is_redpack_post: data.isRedpackPost
    }
    if (data.location) {
      formData.address_name = data.location.name,
      formData.address = data.location.address,
      formData.latitude = data.location.latitude,
      formData.longitude = data.location.longitude
    }
    request(url, 'POST', app.globalData.loginToken, formData, function (err, data) {
      console.log(err)
      if (!err) {
        // 创建post成功，上传图片
        that._uploadMedias(data, function(err) {
          wx.hideLoading()
          /*
          let content = '发布成功'
          if (err) {
            content = '发布成功，但有' + err.errNum + '个文件上传失败' 
          }
          */
          wx.showToast({
            title: '发布成功',
            success: function() {
              let obj = { cnum: that.data.medias.length }
              WxNotificationCenter.postNotificationName('refreshPosts', obj)
              wx.navigateBack({
                delta: 1
              })
            }
          })
        })
      }
    })
  },

  /*
   * 上传选择的文件
   * 递归处理
   * 记录上传失败的个数
   */
  _uploadMedias(post, callback) {
    let index = 0
    let that = this
    let error = { 'code': 0, 'errNum': 0 }
    let uploadMedia = function() {
      let mediaElem = that.data.medias[index]
      let ext = mediaElem.path.split('.').pop()
      // 上传需要设置设置key
      let date = new Date()
      // TODO 还是需要将文件名在时间戳的基础上做处理
      let timestamp = Math.round(date.getTime())
      let key = 'attach/' + date.getFullYear() + '/' + date.getMonth() + '/' + date.getDay() + '/' + timestamp + '.' + ext
      // 先上传头像图片
      let options = {
        region: 'SCN',
        domain: 'xiaoduwu-data.eqiqu.mobi',
        uptoken: that.data.upToken,
      }
      qiniuUploader.init(options)
      let params = [
        { 'key': 'x:post', 'value': post.id },
        { 'key': 'x:author', 'value': that.data.account.id },
        { 'key': 'x:file_name', 'value': key },
        { 'key': 'key', 'value': key },
      ]
      qiniuUploader.upload(mediaElem.path, params, (res) => {
        index ++;
        if (index >= that.data.medias.length) {
          if (error.code) {
            return callback(error)
          } else {
            return callback(null)
          }
        } else {
          uploadMedia()
        }
      }, (err) => {
        index ++
        error.code = 1
        error.errNum ++
        if (index >= that.data.medias.length) {
          if (error.code) {
            return callback(error)
          } else {
            return callback(null)
          }
        } else {
          uploadMedia()
        }
      })
    }
    // 递归上传文件
    uploadMedia()
  },


})